package com.liush.system.service.impl;

import com.liush.model.controller.SysUser;
import com.liush.system.custom.CustomUser;
import com.liush.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;


@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.getByUserName(username);
        if (null == sysUser) {
            throw new UsernameNotFoundException("用户名不存在！");
        }

        if (sysUser.getStatus().intValue() == 0) {
            throw new RuntimeException("账号已停用");
        }

        //获取用户的权限信息
        List<String> userPermsBtnsList = sysUserService.getUserPermsBtnsByUserId(sysUser.getId());

        //权限集合
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        for (String perms : userPermsBtnsList) {
            authorities.add(new SimpleGrantedAuthority(perms));
        }
        return new CustomUser(sysUser, authorities);
    }
}